package com.ghca.myinfo3.system.service.impl;

import com.ghca.myinfo3.system.entity.Department;
import com.ghca.myinfo3.system.entity.User;
import com.ghca.myinfo3.system.repository.DepartmentRepository;
import com.ghca.myinfo3.system.repository.UserRepository;
import com.ghca.myinfo3.system.service.IUserService;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/18.
 */

@Service
public class UserService implements IUserService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private DepartmentRepository departmentRepository;

    @Transactional
    @Override
    public User login(String username, String password) {
        User user = userRepository.findByUsername(username);
        return user != null && password.equals(user.getPassword()) ? user : null;
    }


    @Transactional
    @Override
    public User addUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public List<User> list(User example) {
        return userRepository.findAll(Example.of(example));
    }

    @Override
    public List<User> list(Long deptId) {
        List<User> list = new ArrayList<>();
        List<Department> departments = departmentRepository.findByParentId(deptId);
        for (Department department : departments) {
            List<User> users = userRepository.findByDepartment(department);
            list.addAll(users);
        }
        return list;
    }
}
